#!/bin/sh

. "$SPEC_PATH/abstract/backup"

e2e_test_extra_hash() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
    "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/abstract/backup")"
}

e2e_test_install() {
  install_minio

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 2 \
    --set-string configurations.postgresconfig.postgresql\\.conf.wal_keep_size=0

  wait_pods_running "$CLUSTER_NAMESPACE" 3
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1

  wait_pods_terminated "$CLUSTER_NAMESPACE" 2

  generate_mock_data
  for INDEX in $(seq 1 16)
  do
    rotate_wal_file > /dev/null
  done
}

e2e_test() {
  run_test "Checking that replica can catch-up from backup storage" check_replica_can_catch_up_from_backup_storage
}

check_replica_can_catch_up_from_backup_storage() {
  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 2

  wait_pods_running "$CLUSTER_NAMESPACE" 3

  local RESULT EXIT_CODE
  try_function wait_until check_mock_data_replication "$CLUSTER_NAME"
  if "$RESULT"
  then
    success "Replica catch-up from backup storage"
  else
    fail "Replica didn't catch-up from backup storage"
  fi
}
